package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.PushGroupFormDto;
import cn.livingCloud.entity.core.PushGroup;
import cn.livingCloud.repository.PushGroupMapper;
import cn.livingCloud.service.QuartzJobService;
import org.apache.commons.lang.StringUtils;
import org.quartz.SchedulerException;

/**
 * Created by DingJie on 2016/6/21.
 */
public class PushGroupFormDtoUpdater {
    protected transient PushGroupMapper mapper = BeanProvider.getBean(PushGroupMapper.class);
    protected transient QuartzJobService jobService = BeanProvider.getBean(QuartzJobService.class);

    private PushGroupFormDto formDto;

    public PushGroupFormDtoUpdater(PushGroupFormDto formDto) {
        this.formDto = formDto;
    }

    public void update() {
        PushGroup pushGroup;
        if (StringUtils.isEmpty(formDto.getUuid())) {
            pushGroup = new PushGroup();
            pushGroup.setName(formDto.getName());
            pushGroup.setCronExpression(formDto.getCronExpression());
            pushGroup.setReportRuleUuid(formDto.getReportRuleUuid());
            mapper.insert(pushGroup);
        } else {
            pushGroup = mapper.selectByPrimaryKey(formDto.getUuid());
            pushGroup.setName(formDto.getName());
            pushGroup.setCronExpression(formDto.getCronExpression());
            pushGroup.setReportRuleUuid(formDto.getReportRuleUuid());
            mapper.updateByPrimaryKey(pushGroup);
        }

        //启用定时推送
        if (!pushGroup.getArchive() && StringUtils.isNotEmpty(pushGroup.getCronExpression())) {
            try {
                jobService.addJob(pushGroup);
            } catch (SchedulerException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public PushGroupFormDto getFormDto() {
        return formDto;
    }

    public void setFormDto(PushGroupFormDto formDto) {
        this.formDto = formDto;
    }
}
